<?php

namespace App\Console\Commands;

use App\Accounts;
use App\RemoteAccountsV2;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class FillAccount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'FillAccount';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';


    //实际推送条数
    private $push_num = 0;

    // 实际新增条数
    private $bl_num = 0;

    // 删除去重数据
    private $del_num = 0;

    //
    private $fjId = 20000000;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->qc();

        echo "推送了".$this->push_num."条数据";
        echo "----\r\n";
        echo '补充丢失数据'.$this->bl_num.'条数据';
        echo "----\r\n";
        echo '删除去重数据'.$this->del_num.'条数据';
        echo "----\r\n";
    }


    // 第一步： 去重处理
    private function qc(){
        $sql = 'select count(id) as id_num,id,appid,name from meta_accounts group by appid,name HAVING id_num > 1 order by id_num desc';
        $select = DB::connection()->select($sql);
        foreach ($select as $one){
            if ($one){
                
                $bool = DB::connection()->statement('delete from meta_accounts where appid=? and name=? and id !=?',[$one->appid,$one->name,$one->id]);
                if ($bool){
                    $this->del_num++;
                }
                
            
                // $sql = 'delete from meta_accounts where appid="'.$one->appid.'" and name="'.$one->name.'" and id !='.$one->id;
                // $del_num = DB::connection()->delete($sql);
                // $this->del_num += $del_num;
            }
        }

        $this->doDiff();
    }

    // 第二步： 根据差异，回填  select count(id) from  where appid='com.belljohncla.collageai'   45714  45879
    //  ALTER TABLE `meta_accounts` ADD COLUMN `push_id` tinyint UNSIGNED NULL DEFAULT 0 COMMENT '是否已推送，0未推送' AFTER `account_id`;
    private function doDiff(){
        $addAccounts = RemoteAccountsV2::where('push_id','=',0)->select(['id','appid','name'])->limit(2000)->get()->toArray();
        if ($addAccounts){
            foreach ($addAccounts as $row)
            {
                // 查询有没有
                $id = Accounts::where(['appid' => $row['appid'],'name' => $row['name']])->value('id');
                if ($id){
                    $one = DB::connection("mysql_47_v2")->table('meta_accounts')
                        ->where('id', '=', $row['id'])
                        ->update(['push_id' => 1]);

                    if ($one){
                        Accounts::where('id', $id)->update(['source_id' => ($row['id'] + $this->fjId)]);
                        $this->push_num++;
                    }
                }else{
//                    则需要同步数据
                    $nums = $this->_getDataV2($row['id']);
                    if ($nums){
                        // 说明同步成功了
                        $id = Accounts::where(['appid' => $row['appid'],'source_id' => ($row['id'] + $this->fjId)])->value('id');
                        if ($id){
                            $one = DB::connection("mysql_47_v2")->table('meta_accounts')
                                ->where('id', '=', $row['id'])
                                ->update(['push_id' => 1]);
                            if ($one){
                                $this->bl_num++;
                                $this->push_num++;
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 处理单条数据
     * @param $rid
     * @return int
     */
    private function _getDataV2($rid){
        $addAccounts = RemoteAccountsV2::where('id','=',$rid)->limit(10)->get()->toArray();

        $count = 0;
        foreach ($addAccounts as $account){
            $newAccount = new Accounts();
            $newAccount->appId = $account['appId'];
            $newAccount->ua = $account['ua'];
            $newAccount->name = $account['name'];
            $newAccount->pass = $account['pass'];
            $newAccount->cookies = $account['cookies'];
            $newAccount->accessToken = $account['accessToken'];
            $newAccount->graphData = $account['graphData'];
            $newAccount->ip = $account['ip'];
            $newAccount->country = $account['country'];
            $newAccount->status = $account['status'];
            $newAccount->create_time = $account['create_time'];
            $newAccount->update_time = $account['update_time'];
            $newAccount->bm = $account['bm'];
            $newAccount->page = $account['page'];
            $newAccount->adaccount = $account['adaccount'];
            $newAccount->bill = $account['bill'];
            $newAccount->is_prepay_account = $account['is_prepay_account'];
            $newAccount->page_created_time = $account['page_created_time'];
            $newAccount->bm_created_time = $account['bm_created_time'];
            $newAccount->source_id = ($account['id'] + $this->fjId);
            $graphData = json_decode($account['graphData'],true);
            //广告账户信息
            if (isset($graphData['adaccounts'])) {
                if (isset($graphData['adaccounts']['data'][0]['account_id']) && $account_id = $graphData['adaccounts']['data'][0]['account_id']){
                    $newAccount->account_id = $account_id;
                }

                foreach ($graphData['adaccounts']['data'] as $key => $value) {
                    $adtrust_dsl_usd = $value['currency'] == 'USD' || $value['adtrust_dsl']==-1 ? $value['adtrust_dsl'] : $value['adtrust_dsl'] / $value['account_currency_ratio_to_usd'];
                    //取最大的活或者欠费的账户的信息
                    if (($newAccount->adtrust_dsl_usd < $adtrust_dsl_usd&&in_array($value['account_status'],[1,3]))||($adtrust_dsl_usd==-1&&in_array($value['account_status'],[1,3]))){
                        $newAccount->adaccount++;
                        if ($value['amount_spent'] > 0) {
                            $newAccount->bill++;
                        }
                        $newAccount->currency = $value['currency'];
                        $newAccount->account_status = $value['account_status'];
                        $newAccount->adtrust_dsl = $value['adtrust_dsl'];
                        $newAccount->adtrust_dsl_usd = $adtrust_dsl_usd;
                        $newAccount->is_prepay_account = (int)$value['is_prepay_account'];
                        $newAccount->amount_spent = $value['amount_spent'];
                    }
                }
            }
            //page信息
            if (isset($graphData['accounts'])) {
                foreach ($graphData['accounts']['data'] as $key => $value) {
                    if ($newAccount->page_created_time > $value['page_created_time'] || !$newAccount->page_created_time) {
                        $newAccount->page_created_time = $value['page_created_time'];
                    }
                }
            }
            //bm信息
            if (isset($graphData['businesses'])) {
                foreach ($graphData['businesses']['data'] as $key => $value) {
                    if ($newAccount->bm_created_time > $value['created_time'] || !$newAccount->bm_created_time) {
                        $newAccount->bm_created_time = $value['created_time'];
                    }
                }
            }
            $newAccount->save();
            $count++;
        }
        return $count;
    }
}
